package models

import (
	"errors"
	"time"
)

// table articles
type Article struct {
	ID		int     `gorm:"primary_key"`
	Title	string	`gorm:"type:varchar(40);not null"`
	Content	string	`gorm:"type:text"`
}

// Query all articles
func GetAllArticles() ([]*Article, error) {
	var articles []*Article
	err := DB.Find(&articles).Error
	if err != nil {
		return nil, err
	}
	return articles, nil
}

// Query article by id
func GetArticleById(id int) (*Article, error) {
	var article Article
	err := DB.Where("id=?", id).First(&article).Error
	if err != nil {
		return nil, errors.New("Article not found")
	}
	return &article, nil
}

// create an article
func (self *Article) Create() error {
	err := DB.Create(self).Error
	return err
}

// delete an article, need ID field
func (self *Article) Delete() error {
	err := DB.Delete(self).Error
	return err
}

// update an article, need ID field
func (self *Article) Update() error {
	affect := DB.Model(&self).Update(self).RowsAffected
	if affect == 0 {
		return errors.New("No such article")
	}
	return nil
}

// remove all articles
func RemoveAllArticles() {
	go func() {
		time.Sleep(5*time.Second)
		DB.Model(&Article{}).Delete(&Article{})
	}()
}
